import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Profile from '../views/Profile.vue'
import Community from '../views/Community.vue'
import Inspiration from '../views/Inspiration.vue'
import Painting from '../views/Painting.vue'
import Music from '../views/Music.vue'
import Writing from '../views/Writing.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login,
      meta: { requiresAuth: false }
    },
    {
      path: '/home',
      name: 'Home',
      component: Home,
      meta: { requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'Profile',
      component: Profile,
      meta: { requiresAuth: true }
    },
    {
      path: '/community',
      name: 'Community',
      component: Community,
      meta: { requiresAuth: true }
    },
    {
      path: '/inspiration',
      name: 'Inspiration',
      component: Inspiration,
      meta: { requiresAuth: true }
    },
    {
      path: '/painting',
      name: 'Painting',
      component: Painting,
      meta: { requiresAuth: true }
    },
    {
      path: '/music',
      name: 'Music',
      component: Music,
      meta: { requiresAuth: true }
    },
    {
      path: '/writing',
      name: 'Writing',
      component: Writing,
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 检查用户是否已登录（检查localStorage中是否存在token）
    const token = localStorage.getItem('token')
    if (token) {
      // 已登录，允许访问
      next()
    } else {
      // 未登录，重定向到登录页
      next('/')
    }
  } else {
    // 不需要认证的路由，直接访问
    next()
  }
})

export default router